//
//  TeacherViewController.m
//  CoreDataTest
//
//  Created by wangrui on 14-2-28.
//  Copyright (c) 2014年 Ourui. All rights reserved.
//

#import "TeacherViewController.h"
#import "Teacher.h"

@interface TeacherViewController()<NSFetchedResultsControllerDelegate>{
    NSFetchedResultsController *_fechedResultContrller;
}

@end

@implementation TeacherViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mergeChanges:)
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:nil];
    
    UIBarButtonItem *add = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addTeacherInOtherThread:)];
     UIBarButtonItem *del = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(delTeacher:)];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:add,del,nil];
}

- (void)addTeacher:(id)sender{
    NSEntityDescription *descroption = [NSEntityDescription entityForName:@"Teacher" inManagedObjectContext:self.mainObjectCtx];
    Teacher *t = [[Teacher alloc] initWithEntity:descroption insertIntoManagedObjectContext:self.mainObjectCtx];
    t.num = [NSNumber numberWithInt:arc4random()%1000];
    t.name = [NSString stringWithFormat:@"name:%@",t.num];
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Teacher"];
    request.predicate = [NSPredicate predicateWithFormat:@"num = %@",t.num];
    
    NSArray *resluts = [self.mainObjectCtx executeFetchRequest:request error:nil];
    if (!(resluts.count>0)) {
        [self.mainObjectCtx insertObject:t];
    }
    
    if ([self.mainObjectCtx hasChanges]) {
        [self.mainObjectCtx save:nil];
    }
    
}

- (void)delTeacher:(id)sender{

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Teacher"];
    NSArray *resluts = [self.mainObjectCtx executeFetchRequest:request error:nil];
    
    if (resluts.count>0) {
        [self.mainObjectCtx deleteObject:resluts.lastObject];
    }
    
    if ([self.mainObjectCtx hasChanges]) {
        [self.mainObjectCtx save:nil];
    }
}


#pragma mark - safe solution

- (void)addTeacherInOtherThread:(id)sender{
    [NSThread detachNewThreadSelector:@selector(reallyAdd:) toTarget:self withObject:nil];
    
}

- (void)reallyAdd:(id)sender{
    NSManagedObjectContext *ctx = [[NSManagedObjectContext alloc]init];
    ctx.persistentStoreCoordinator = self.coordinator;
    
    
    NSEntityDescription *descroption = [NSEntityDescription entityForName:@"Teacher" inManagedObjectContext:ctx];
    Teacher *t = [[Teacher alloc] initWithEntity:descroption insertIntoManagedObjectContext:ctx];
    t.num = [NSNumber numberWithInt:arc4random()%1000];
    t.name = [NSString stringWithFormat:@"name:%@",t.num];
    
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Teacher"];
    request.predicate = [NSPredicate predicateWithFormat:@"num = %@",t.num];
    
    NSArray *resluts = [ctx executeFetchRequest:request error:nil];
    if (!(resluts.count>0)) {
        [ctx insertObject:t];
    }
    
    if ([ctx hasChanges]) {
        [ctx save:nil];
    }
}

- (void)updateMainContex:(NSNotification *)noti{
    [self.mainObjectCtx mergeChangesFromContextDidSaveNotification:noti];
}

- (void)mergeChanges:(NSNotification *)noti{
    [self performSelectorOnMainThread:@selector(updateMainContex:) withObject:noti waitUntilDone:NO];
}

- (NSFetchedResultsController *)fechedResultContrller{
    if (!_fechedResultContrller) {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Teacher"];
        NSSortDescriptor *des = [[NSSortDescriptor alloc]initWithKey:@"num" ascending:NO];
        [request setSortDescriptors:[NSArray arrayWithObjects:des,nil]];
         
         NSFetchedResultsController *fc = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                              managedObjectContext:self.mainObjectCtx
                                                                                sectionNameKeyPath:nil
                                                                                         cacheName:nil];
        fc.delegate = self;
        [fc performFetch:nil];
        
         _fechedResultContrller = fc;
        
    }
    return _fechedResultContrller;
}

#pragma mark - UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.fechedResultContrller.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"teacherCell" forIndexPath:indexPath];
    UILabel *numLabel = (UILabel *)[cell.contentView viewWithTag:1];
    UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:2];
    
    Teacher *teacher = (Teacher *)[self.fechedResultContrller objectAtIndexPath:indexPath];
    numLabel.text = [teacher.num stringValue];
    nameLabel.text = teacher.name;
    
    return cell;
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
    [self.tableView reloadData];
}

@end
